import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

// Nikolas Wolfe
// 2/25/09
// CNT 4007
// Program 1: Client-Server

public class Server
{
	// defaults
	private static int port = 6336;
	private static final String add = "add";
	private static final String multiply = "multiply";
	
	public static void main(String args[]) throws IOException
	{
		// data to reply with
		String inputData, outputData = "";
		ServerSocket serverSocket = null;
		
		try
		{
			// Start the server socket
			System.out.print("Starting server... ");
			serverSocket = new ServerSocket(Integer.parseInt(args[0]));
			System.out.println("Done!");
		}
		catch( Exception e )
		{
			System.out.println("Server initialization failed!\n");
			serverSocket = new ServerSocket(port);
		}
		
		// control loop
		while(true)
		{
			// set up connection socket
			Socket connectionSocket = serverSocket.accept();
			BufferedReader inFromClient = new BufferedReader(
					new InputStreamReader(connectionSocket.getInputStream()));
			DataOutputStream outToClient = new DataOutputStream(
					connectionSocket.getOutputStream());
			
			// read input from client
			inputData = inFromClient.readLine();
			System.out.println("Data received: " + inputData);
			
			// parse data
			String[] inputArr = inputData.split(" ");
			if( !(inputArr[0].trim().equals(add) || inputArr[0].trim().equals(multiply)) )
			{
				outputData = invertCase(inputData);
			}
			else if( inputArr[0].trim().equals(add) )
			{
				try
				{
					int x, y;
					x = Integer.parseInt(inputArr[1]);
					y = Integer.parseInt(inputArr[2]);
					outputData = "" + add(x, y);
				} catch (NumberFormatException nfe)
				{
					outputData = "number argument incorrectly formatted!";
				}
			}
			else if( inputArr[0].trim().equals(multiply) )
			{
				try
				{
					int x, y;
					x = Integer.parseInt(inputArr[1]);
					y = Integer.parseInt(inputArr[2]);
					outputData = "" + multiply(x, y);
				} catch (NumberFormatException nfe)
				{
					outputData = "number argument incorrectly formatted!";
				}
			}
			outToClient.writeBytes( outputData + '\n');
		}
	}
	
	private static int multiply(int x, int y)
	{
		return x * y;
	}
	
	private static int add(int x, int y)
	{
		return x + y;
	}
	
	private static String invertCase(String s)
	{
		StringBuilder retString = new StringBuilder();
		char[] arr = s.toCharArray();
		for(int i = 0; i < arr.length; i++)
		{
			String q = "" + arr[i];
			if((int)arr[i] < 97) // if uppercase
			{
				retString.append(q.toLowerCase());
			}
			else
			{
				retString.append(q.toUpperCase());
			}
		}
		return retString.toString();
	}
}
